package march;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import quads.MarchQuad;
import save.Performance;

public class Timekeeper {

	Timer timer;
	public static final int period = 63;
	
	private GridCanvas canvas;
	private List<MarchQuad> quads;

	public static Timekeeper instance;
	
	private Performance performance;
	
	
	public static Timekeeper get() {
		if (instance == null) {
			System.out.println("Creating timekeeper singleton on demand");
			instance = new Timekeeper();
		}
		
		return instance;
	}
	
	
	public Timekeeper() {
		
		instance = this;
		
		quads = new ArrayList<MarchQuad>();
		canvas = new GridCanvas(quads);
		
		timer = new Timer();
		
		TimerTask tt = new TimerTask() {
			
			public void run() {
				update();
				
			}
		};
		
		
		timer.scheduleAtFixedRate(tt, 0, period);
	}
	
	
	private void update() {
		
		boolean changed = false;
		
		for (MarchQuad mq : quads) {
			changed = mq.handlePulse() || changed;
		}
		
		if (canvas != null) {
		
			canvas.handlePulse();
			
			if (changed) {
				canvas.repaint();
			}
		
		}
		
		if (performance != null) {
			if (!performance.handleTimestep()) {
				performance = null;
			}
		}
	}
	
	public void playPerformance(Performance p) {
		this.performance = p;
	}


	public GridCanvas getGridCanvas() {
		return canvas;
	}


	public void clearQuads() {
		quads.clear();
		
	}
	
}
